package com.aaa.zuul.filter;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.aaa.zuul.service.RemoteLoginService;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Xiujie Yu
 * @Date 2021-01-22
 * @Time 9:37
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Autowired
    private RemoteLoginService remoteLoginService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤器业务代码
        //使用zuul中提供的请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取response
        HttpServletResponse response = currentContext.getResponse();
        //获取request
        HttpServletRequest request = currentContext.getRequest();

        //获取请求的URI
        String requestURI = request.getRequestURI();
        //获取请求的携带的token
        //需要请求时，所有请求都加
        String token = request.getHeader("myAuthorization");
        // String accessToken = request.getParameter("accessToken");
        if (requestURI.contains("/ms/member/insertMember")
                || requestURI.contains("/ms/member/queryMemberByParam")
                || requestURI.contains("/ms/member/sentSM")
                || requestURI.contains("/sso/memberLogin/auth")
                || requestURI.contains("/sso/userLogin/auth")
                || requestURI.contains("/ms/member/passwordBack")
                || (!StringUtils.isEmpty(token) && remoteLoginService.checkToken(token))) {
            //验证通过，放行
            currentContext.setSendZuulResponse(true);
            currentContext.setResponseStatusCode(HttpStatus.SC_OK);
        } else {
            currentContext.setSendZuulResponse(false);
            try {
                Result<String> result = new Result<>(ResultStatus.FAIL.getCode(),
                        ResultStatus.FAIL.getMessage(), "noLogin");
                String s = JSON.toJSONString(result);
                response.setCharacterEncoding("GBK");
                //放回noLogin
                response.getWriter().print(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
